package controller;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import pojo.ArchivePojo;
import pojo.UsersPojo;
import service.ArchiveService;
import service.UserlogService;
import service.UsersService;

@Controller
public class UserController {
	UsersService serviceUser = new UsersService();
	UserlogService serviceLog = new UserlogService();
	ArchiveService serviceSer = new ArchiveService();

	@RequestMapping(value = "/login.action", method = RequestMethod.POST)
	@ResponseBody
	public String login(
			@RequestParam(value = "account", defaultValue = "") String account,
			@RequestParam(value = "password", defaultValue = "") String password,
			HttpServletResponse response// 从后台到前台用response 从前台到后台用request
	) {
		UsersPojo user = serviceUser.queryone(account, password);
		if ("0".equals(user.getCounter())) {
			return "ERR";
		}
		// ID是int的时候用String.valueOf(user.getId())转换类型
		response.addCookie(new Cookie("user", user.getId()));
		serviceLog.addlog(user.getId(), "0", "登录");
		return "OK";
	}

	@RequestMapping(value = "/logout.action", method = RequestMethod.POST)
	@ResponseBody
	public String logout(
			@CookieValue(value = "user", defaultValue = "") String user_id,
			HttpServletResponse response) {
		ArchivePojo ar = serviceSer.queryid();
		response.addCookie(new Cookie("user", null));
		serviceLog.addlog(user_id, String.valueOf(ar.getId()), "退出");
		return "OK";
	}

	@RequestMapping(value = "/querynickname.action", method = RequestMethod.GET)
	@ResponseBody
	public List<UsersPojo> querynickname(
			@CookieValue(value = "user", defaultValue = "") String user_id) {
		List<UsersPojo> u = serviceUser.querynickname(user_id);
		return u;
	}
}